package site.mingdao.boot.web.config;

import jakarta.annotation.Nonnull;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import site.mingdao.boot.common.pojo.Result;
import site.mingdao.boot.common.util.json.JsonUtils;
import site.mingdao.boot.web.core.annotations.IgnoreRestControllerResponseAdvice;

@RestControllerAdvice
public class ControllerAdviceAutoConfiguration implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(@Nonnull MethodParameter returnType, @Nonnull Class<? extends HttpMessageConverter<?>> converterType) {
        return !(returnType.hasMethodAnnotation(IgnoreRestControllerResponseAdvice.class)
                || returnType.getParameterType().isAssignableFrom(Result.class)
                || returnType.getDeclaringClass().getName().contains("springdoc"));
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body,
                                  @Nonnull MethodParameter returnType,
                                  @Nonnull MediaType selectedContentType,
                                  @Nonnull Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  @Nonnull ServerHttpRequest request,
                                  @Nonnull ServerHttpResponse response) {
        if (body instanceof String) {
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return JsonUtils.toJsonString(Result.success(body));
        }
        return Result.success(body);
    }

}
